package com.swingson.easydrag;

import java.awt.Component;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

/**
 * Generic Transferrable that contains the Source Component and the data Object
 * ready for transport.
 * 
 * @author Mohamed Mansour
 */
public class GenericTransferable implements Transferable {

    private final Object item;
    private final Component source;

    public static DataFlavor ITEM_FLAVOR = null;
    public static DataFlavor SOURCE_COMPONENT_FLAVOR = new DataFlavor(
            DataFlavor.javaJVMLocalObjectMimeType,
            "SourceComponent");

    public GenericTransferable(Object item, Component source) {
        ITEM_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, item
                .getClass().getCanonicalName());
        this.item = item;
        this.source = source;
    }

    @Override
    public Object getTransferData(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException {
        if (flavor == ITEM_FLAVOR) {
            return item;
        } else if (flavor == SOURCE_COMPONENT_FLAVOR) {
            return source;
        } else {
            throw new UnsupportedFlavorException(flavor);
        }
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[]{
            ITEM_FLAVOR,
            SOURCE_COMPONENT_FLAVOR};
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return ITEM_FLAVOR.equals(flavor);
    }

    /**
     * @return contents of the data being dragged.
     */
    public Object getItem() {
        return item;
    }

    /**
     * The source the data been dragged from.
     * 
     * @return
     */
    public Component getSource() {
        return source;
    }
}
